package com.wk.springframework.beans.factory.support;

import com.wk.springframework.beans.factory.FactoryBean;
import com.wk.springframework.beans.factory.config.BeanDefinition;
import com.wk.springframework.beans.factory.config.BeanPostProcessor;
import com.wk.springframework.utils.ClassUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 定义好模板,具体的由子类实现
 */
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {


    private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();


    /** BeanPostProcessors to apply in createBean */
    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();

    @Override
    public Object getBean(String beanName) {
        return doGetBean(beanName);
    }

    /**
     * 1.gain a bean from singleton cache
     * 2.if null，do getObjectForBeanInstance
     * 3.create bean from getBeanDefinition&createBean method
     * 4.finally do getObjectForBeanInstance again
     * @param beanName
     * @param args
     * @return
     */
    public <T> T doGetBean(String beanName, Object... args) {
        Object sharedInstance = getSingleton(beanName);
        if (sharedInstance != null) {
            // 如果是 FactoryBean，则需要调用 FactoryBean#getObject
            return (T) getObjectForBeanInstance(sharedInstance, beanName);
        }

        BeanDefinition beanDefinition = getBeanDefinition(beanName);
        Object bean = createBean(beanName, beanDefinition, args);
        return (T) getObjectForBeanInstance(bean, beanName);
    }

    private Object getObjectForBeanInstance(Object beanInstance, String beanName) {
        if (!(beanInstance instanceof FactoryBean)) {
            return beanInstance;
        }

        Object object = getCachedObjectForFactoryBean(beanName);

        if (object == null) {
            FactoryBean<?> factoryBean = (FactoryBean<?>) beanInstance;
            object = getObjectFromFactoryBean(factoryBean, beanName);
        }

        return object;
    }


    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
    }

    public List<BeanPostProcessor> getBeanPostProcessors() {
        return this.beanPostProcessors;
    }

    @Override
    public <T> T getBean(String beanName, Class<T> clazz) {
        return (T) doGetBean(beanName);
    }

    @Override
    public Object getBean(String beanName, Object... args) {
        return doGetBean(beanName, args);
    }

    protected abstract BeanDefinition getBeanDefinition(String beanName);

    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args);

    public ClassLoader getBeanClassLoader() {
        return this.beanClassLoader;
    }

}
